package com.woniuxy.movie.order.mq;


import com.woniuxy.movie.commons.core.model.Result;
import com.woniuxy.movie.commons.web.model.PayInfoDTO;
import com.woniuxy.movie.commons.web.util.AlipayUtil;
import com.woniuxy.movie.commons.web.util.OSSUtil;
import com.woniuxy.movie.commons.web.util.StateData;
import com.woniuxy.movie.order.client.ProductClient;
import com.woniuxy.movie.order.dao.OrderInfoMapper;
import com.woniuxy.movie.order.dto.HandlerOrderDto;
import com.woniuxy.movie.order.exception.OrderException;
import com.woniuxy.movie.order.form.ticket.TicketSaledForm;
import com.woniuxy.movie.order.model.OrderInfo;
import com.woniuxy.movie.order.util.QRUtil;
import com.woniuxy.movie.order.util.RedisUtil;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.io.InputStream;
import java.util.UUID;


@Component
public class HandlerOrderComsumer {

    @Autowired
    private AlipayUtil alipayUtil;

    @Autowired
    private OrderInfoMapper orderInfoMapper;

    @Autowired
    private OSSUtil ossUtil;

    @Autowired
    private ProductClient pc;

    @Autowired
    private RedisUtil redisUtil;

    @RabbitListener(
            bindings = {
                    @QueueBinding(
                            value = @Queue(name = "order-queue"),
                            exchange = @Exchange(name = "delay-ex"),
                            key = "order"
                    )
            })
    @Transactional
    public void handler(HandlerOrderDto handlerOrderDto) throws Exception {
        //消费队列中的订单
        //调用支付宝的接口判断本次订单的支付状态
        PayInfoDTO payInfoDTO = alipayUtil.selectPayState(handlerOrderDto.getOrderId());
        OrderInfo orderInfo = orderInfoMapper.selectById(handlerOrderDto.getOrderId());
        if (orderInfo!=null) {
            if ("TRADE_SUCCESS".equals(payInfoDTO.getPayState())){
                if (orderInfo.getOrderState()== StateData.ORDER_STATE_NOPAY){
                    //修改订单状态
                    orderInfo.setOrderState(StateData.ORDER_STATE_PAYED);
                    orderInfo.setOrderPayTime(payInfoDTO.getPayDate());
                    //生成二维码
                    InputStream qr = QRUtil.createQR(orderInfo.getOrderId(),"jpg","https://liucunyi.oss-cn-chengdu.aliyuncs.com/4b25ae6f100b478483c73facc9a07269.jpg");
                    String fileName = UUID.randomUUID().toString().replaceAll("-","")+".jpg";
                    //二维码上传到oss
                    String path = ossUtil.uploadFile(qr,fileName,"liucunyi");
                    //返回oss中的路径保存到数据库
                    orderInfo.setOrderQr(path);
                    //生成取票码
                    // 取时间戳后8位作为生成的数字
                    Long number = System.currentTimeMillis() % 100000000;
                    orderInfo.setOrderNum(number.toString());
                    orderInfoMapper.updateById(orderInfo);
                    //修改票务状态以及其它信息
                    TicketSaledForm ticketSaledForm = new TicketSaledForm();
                    ticketSaledForm.setTicketTime(payInfoDTO.getPayDate());
                    ticketSaledForm.setTicketUser(orderInfo.getOrderUser());
                    ticketSaledForm.setIds(handlerOrderDto.getTicketIds());
                    Result<Integer> saledResult = pc.saveTicketSaled(ticketSaledForm);
                    if (saledResult.getCode()!=200) {
                        throw new OrderException(saledResult.getCode(),saledResult.getMsg());
                    }
                    if (handlerOrderDto.getTicketIds().size()!=saledResult.getData()) {
                        throw new OrderException(1006,"有票务修改已售失败");
                    }
                    //将ticketIds从redis中删除
                    redisUtil.delObject(orderInfo.getOrderId());

                }
            }else {//如果订单是没有支付的状态
                //修改订单状态
                orderInfo.setOrderState(StateData.ORDER_STATE_CANCEL);
                orderInfoMapper.updateById(orderInfo);
                //修改票务状态为正常状态
                Result<Integer> normalResult = pc.saveTicketNormal(handlerOrderDto.getTicketIds());
                if (normalResult.getCode()!=200) {
                    throw new OrderException(normalResult.getCode(),normalResult.getMsg());
                }
                if (handlerOrderDto.getTicketIds().size()!=normalResult.getData()) {
                    throw new OrderException(1006,"有票务修改待售失败");
                }
            }
        }

    }
}
